<template>
	<view class="container">
		<!-- 头部个人资料卡片 -->
		<view class="profile-card animate__animated animate__fadeIn">
			<view class="profile-header">
				<image class="avatar" :src="teacher.avatarUrl" mode="aspectFill" @click="updateAVer"></image>
				<view class="profile-info">
					<view class="name">{{teacher.name}}</view>
					<!-- <view class="title">高级教师</view> -->
					<button class="change-password" @click="changeMyPassWord">
						<uni-icons type="locked" size="16" color="#fff"></uni-icons>
						修改密码
					</button>
				</view>
			</view>
		</view>

		<!-- 个人介绍部分 -->
		<!-- 个人介绍部分 -->
		<view class="section-card animate__animated animate__fadeIn animate__delay-1s">
			<view class="section-header">
				<uni-icons type="person" size="18" color="#4a6ef5"></uni-icons>
				<text class="section-title">个人介绍</text>
				<button class="edit-btn" @click="editBio = !editBio">
					{{ editBio ? '取消' : '编辑' }}
				</button>
			</view>
			<view class="section-content">
				<textarea v-if="editBio" v-model="teacher.bio" placeholder="请输入个人介绍（最多300字）..." class="intro-textarea"
					maxlength="300" auto-height @input="countBioChars"></textarea>
				<view v-else class="intro-content">
					{{ teacher.bio || '暂无个人介绍' }}
				</view>
				<!-- 添加字数统计 -->
				<view v-if="editBio" class="char-count">
					{{ bioCharCount }}/300
				</view>
			</view>
			<button v-if="editBio" class="save-btn" @click="saveBio">保存</button>
		</view>

		<!-- 擅长科目部分 -->
		<view class="section-card animate__animated animate__fadeIn animate__delay-2s">
			<view class="section-header">
				<uni-icons type="star" size="18" color="#4a6ef5"></uni-icons>
				<text class="section-title">擅长科目</text>
				<button class="edit-btn" @click="editSubjects = !editSubjects">
					{{ editSubjects ? '取消' : '编辑' }}
				</button>
			</view>

			<!-- 默认显示的科目标签 -->
			<view v-if="!editSubjects" class="subject-tags">
				<view v-if="teacher.tags && teacher.tags.length > 0" class="tags-container">
					<view v-for="(tag, index) in teacher.tags.split(',')" :key="index" class="subject-tag">
						{{ tag }}
					</view>
				</view>
				<view v-else class="no-subject">暂无擅长科目</view>
			</view>

			<!-- 编辑时的科目选择器 -->
			<view v-if="editSubjects" class="subject-editor">
				<view class="selected-subjects">
					<view v-for="(subject, index) in selectedSubjects" :key="index" class="selected-tag">
						{{ subject }}
						<uni-icons type="close" size="14" color="#fff" @click="removeSubject(index)"></uni-icons>
					</view>
					<view v-if="selectedSubjects.length === 0" class="hint-text">请选择擅长科目</view>
					<view v-if="selectedSubjects.length >= 4" class="hint-text warning">最多选择4个科目</view>
				</view>

				<view class="subject-selector">
					<!-- 学段选择 -->
					<view class="grade-selector">
						<view v-for="grade in gradeOptions" :key="grade.value"
							:class="['grade-option', {active: selectedGrade === grade.value}]"
							@click="selectGrade(grade.value)">
							{{grade.label}}
						</view>
					</view>

					<!-- 科目选择 -->
					<view class="subject-options">
						<view v-for="subject in subjectOptions" :key="subject.value" class="subject-option"
							@click="addSubject(subject.label)">
							{{subject.label}}
						</view>
					</view>
				</view>

				<button class="save-btn" @click="saveSubjects" :disabled="selectedSubjects.length === 0">保存</button>
			</view>
		</view>

		<!-- 密码修改弹窗 -->
		<uni-popup ref="passwordPopup" type="center" :mask-click="false">
			<view class="popup-content">
				<view class="popup-header">
					<uni-icons type="locked" size="20" color="#4a6ef5"></uni-icons>
					<text>修改密码</text>
				</view>
				<view class="popup-body">
					<view class="input-group">
						<input type="password" v-model="oldPassWord" placeholder="请输入原密码" class="input-field" />
					</view>
					<view class="input-group">
						<input type="password" v-model="newPassWord" placeholder="请输入新密码" class="input-field" />
					</view>
				</view>
				<view class="popup-footer">
					<button class="cancel-btn" @click="cancel">取消</button>
					<button class="confirm-btn" @click="submitPassword">确认修改</button>
				</view>
				<view class="contact-info">
					密码忘记请联系李老师<br />17739117397
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
	import {
		globalVariable
	} from '../../configMy.js';


	export default {

		data() {
			return {
				teacher: {
					name: '',
					bio: '',
					phone: '',
					tags: ''
				},
				oldPassWord: '',
				newPassWord: '',
				editBio: false,
				editSubjects: false,
				bioCharCount: 0,
				// 学段选择
				selectedGrade: 'primary',
				gradeOptions: [{
						value: 'primary',
						label: '小学'
					},
					{
						value: 'middle',
						label: '初中'
					}
				],

				// 科目选择
				selectedSubjects: [],
				subjectOptions: [{
						label: '语文',
						value: 'chinese'
					},
					{
						label: '数学',
						value: 'math'
					},
					{
						label: '英语',
						value: 'english'
					},
					{
						label: '物理',
						value: 'physics'
					},
					{
						label: '化学',
						value: 'chemistry'
					},
					{
						label: '生物',
						value: 'biology'
					},
					{
						label: '历史',
						value: 'history'
					},
					{
						label: '地理',
						value: 'geography'
					},
					{
						label: '政治',
						value: 'politics'
					}
				]
			};
		},
		methods: {
			updateAVer() {
				uni.navigateTo({
					url: "/pages/unloadAver/unloadAver"
				})
			},
			changeMyPassWord() {
				this.$refs.passwordPopup.open();
			},

			cancel() {
				this.$refs.passwordPopup.close();
				this.oldPassWord = '';
				this.newPassWord = '';
			},

			submitPassword() {
				let that = this;
				uni.request({
					url: globalVariable + "/changePassWordTeacher?phoneNumber=" + that.teacher.phone +
						"&oldPassWord=" + that.oldPassWord +
						"&newPassWord=" + that.newPassWord,
					method: 'POST',
					success(res) {
						let info = res.data;
						that.cancel();
						if (info.status == 1) {
							uni.showToast({
								title: info.message,
								duration: 2000,
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: info.message,
								duration: 2000,
								icon: 'none'
							});
						}
					},
					fail() {
						uni.showToast({
							title: "服务器错误",
							duration: 2000,
							icon: 'none'
						});
					}
				});
			},
			countBioChars() {
				this.bioCharCount = this.teacher.bio.length;
			},
			saveBio() {
				let that = this;
				const currentSubjects = this.editSubjects ? this.selectedSubjects.join(',') : (this.teacher.tags || '');

				const queryString =
					`phoneNumber=${encodeURIComponent(that.teacher.phone)}&bio=${encodeURIComponent(that.teacher.bio)}&newSubject=${encodeURIComponent(currentSubjects)}`;

				uni.request({
					url: globalVariable + `/changeInfoTeacher?${queryString}`,
					method: 'POST',
					success(res) {
						let info = res.data;
						if (info.status == 1) {
							uni.showToast({
								title: '个人介绍已保存',
								icon: 'success'
							});
							that.editBio = false;
							// 更新本地缓存
							that.teacher.tags = currentSubjects;
							uni.setStorage({
								key: "teacher",
								data: that.teacher
							});
						}
					}
				});
			},

			selectGrade(grade) {
				this.selectedGrade = grade;
			},

			addSubject(subject) {
				if (this.selectedSubjects.length >= 4) {
					uni.showToast({
						title: '最多选择4个科目',
						icon: 'none'
					});
					return;
				}

				// 格式化为"小学语文"或"初中数学"的格式
				const gradePrefix = this.selectedGrade === 'primary' ? '小学' : '初中';
				const fullSubject = `${gradePrefix}${subject}`;

				if (!this.selectedSubjects.includes(fullSubject)) {
					this.selectedSubjects.push(fullSubject);
				} else {
					uni.showToast({
						title: '已添加过该科目',
						icon: 'none'
					});
				}
			},

			removeSubject(index) {
				this.selectedSubjects.splice(index, 1);
			},

			saveSubjects() {
				if (this.selectedSubjects.length === 0) {
					uni.showToast({
						title: '请至少选择一个科目',
						icon: 'none'
					});
					return;
				}

				let that = this;
				const subjectsStr = this.selectedSubjects.join(',');
				const currentSubjects = this.editSubjects ? this.selectedSubjects.join(',') : (this.teacher.tags || '');
				const queryString =
					`phoneNumber=${encodeURIComponent(that.teacher.phone)}&bio=${encodeURIComponent(that.teacher.bio)}&newSubject=${encodeURIComponent(currentSubjects)}`;

				uni.request({
					url: globalVariable + `/changeInfoTeacher?${queryString}`,
					method: 'POST',
					success(res) {
						let info = res.data;
						if (info.status == 1) {
							uni.showToast({
								title: '科目设置已保存',
								icon: 'success'
							});
							that.editSubjects = false;
							// 更新本地缓存
							that.teacher.tags = subjectsStr;
							uni.setStorage({
								key: "teacher",
								data: that.teacher
							});
						}
					}
				});
			},

			initSelectedSubjects() {
				if (this.teacher.tags) {
					// 确保科目是用英文逗号分隔的
					this.selectedSubjects = this.teacher.tags.split(',').filter(item => item.trim() !== '');
				}
			}
		},
		 onShow() {
		    // 如果已经有teacher数据，重新加载头像
		    if (this.teacher.avatarUrl) {
		      const timestamp = new Date().getTime();
		      // 如果是默认头像就不处理
		      if (!this.teacher.avatarUrl.startsWith('/static')) {
		        this.teacher.avatarUrl = `${globalVariable}/get/${this.teacher.avatarUrl.split('/').pop().split('?')[0]}?t=${timestamp}`;
		      }
		    }
		  },
		onLoad() {
			let that = this;
			uni.getStorage({
				key: "teacher",
				success: function(res) {
					that.teacher = res.data;
					// 处理头像URL，添加时间戳参数
					if (that.teacher.avatarUrl == null) {
						that.teacher.avatarUrl = "/static/aver.jpg";
					} else {
						// 添加时间戳参数防止缓存
						const timestamp = new Date().getTime();
						that.teacher.avatarUrl =
							`${globalVariable}/get/${that.teacher.avatarUrl}?t=${timestamp}`;
					}

					// 初始化科目数据
					that.initSelectedSubjects();
					// 如果没有tags，初始化为空字符串
					if (!that.teacher.tags) {
						that.teacher.tags = '';
					}
					// 如果没有bio，初始化为空字符串
					if (!that.teacher.bio) {
						that.teacher.bio = '';
					}
				}
			});
		}
	};
</script>
<style scoped>
	@import url("https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css");
	/* 基础样式 */
	.container {
		padding: 20rpx;
		background: linear-gradient(to bottom, #f5f7fa, #e4e8f0);
		min-height: 100vh;
	}

	/* 个人资料卡片 */
	.profile-card {
		background: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.05);
	}

	.profile-header {
		display: flex;
		align-items: center;
	}

	.avatar {
		width: 140rpx;
		height: 140rpx;
		border-radius: 50%;
		border: 4rpx solid #f0f4ff;
		box-shadow: 0 4rpx 12rpx rgba(74, 110, 245, 0.2);
	}

	.profile-info {
		margin-left: 30rpx;
		flex: 1;
	}

	.name {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}

	.title {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 20rpx;
	}

	.change-password {
		background: linear-gradient(to right, #4a6ef5, #6a5af9);
		color: white;
		border-radius: 50rpx;
		padding: 10rpx 24rpx;
		font-size: 26rpx;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 12rpx rgba(74, 110, 245, 0.3);
	}

	/* 通用卡片样式 */
	.section-card {
		background: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.05);
	}

	.section-header {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f4ff;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-left: 12rpx;
		flex: 1;
	}

	.edit-btn {
		background: transparent;
		color: #4a6ef5;
		font-size: 26rpx;
		padding: 8rpx 16rpx;
		border: 1rpx solid #4a6ef5;
		border-radius: 50rpx;
	}

	/* 个人介绍 */
	.intro-textarea {
		width: 100%;
		min-height: 150rpx;
		/* padding: 20rpx; */
		border-radius: 12rpx;
		background-color: #f8f9ff;
		font-size: 28rpx;
		line-height: 1.6;
		border: 1rpx solid #e0e6ff;
	}

	.intro-content {
		padding: 20rpx;
		font-size: 28rpx;
		line-height: 1.6;
		color: #666;
	}

	.save-btn {
		background: linear-gradient(to right, #4a6ef5, #6a5af9);
		color: white;
		width: 100%;
		border-radius: 50rpx;
		padding: 24rpx 0;
		font-size: 30rpx;
		font-weight: bold;
		margin-top: 20rpx;
	}

	/* 擅长科目标签 */
	.subject-tags {
		padding: 0 20rpx;
	}

	.tags-container {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.subject-tag {
		background: #f0f4ff;
		color: #4a6ef5;
		padding: 12rpx 24rpx;
		border-radius: 50rpx;
		font-size: 26rpx;
	}

	.no-subject {
		color: #999;
		font-size: 26rpx;
		padding: 20rpx;
		text-align: center;
	}

	/* 科目编辑器 */
	.subject-editor {
		padding: 0 10rpx;
	}

	.selected-subjects {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin-bottom: 30rpx;
		min-height: 80rpx;
	}

	.selected-tag {
		background: #4a6ef5;
		color: white;
		padding: 12rpx 24rpx;
		border-radius: 50rpx;
		font-size: 26rpx;
		display: flex;
		align-items: center;
	}

	.char-count {
		text-align: right;
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.hint-text {
		color: #999;
		font-size: 26rpx;
		width: 100%;
		padding: 10rpx 0;
	}

	.hint-text.warning {
		color: #ff4d4f;
	}

	/* 学段选择 */
	.grade-selector {
		display: flex;
		margin-bottom: 30rpx;
		border-radius: 12rpx;
		overflow: hidden;
		background: #f8f9ff;
	}

	.grade-option {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 28rpx;
		color: #666;
	}

	.grade-option.active {
		background: linear-gradient(to right, #4a6ef5, #6a5af9);
		color: white;
		font-weight: bold;
	}

	/* 科目选择 */
	.subject-options {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.subject-option {
		background: #f8f9ff;
		color: #666;
		padding: 16rpx 24rpx;
		border-radius: 50rpx;
		font-size: 26rpx;
	}

	.subject-option:active {
		background: #e0e6ff;
	}

	/* 弹窗样式 */
	.popup-content {
		background: white;
		border-radius: 16rpx;
		width: 80%;
		padding: 30rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
	}

	.popup-header {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.popup-header text {
		margin-left: 10rpx;
	}

	.popup-body {
		margin-bottom: 30rpx;
	}

	.input-group {
		margin-bottom: 30rpx;
	}

	.input-field {
		/* width: 100%; */
		padding: 20rpx;
		border-radius: 12rpx;
		background-color: #f8f9ff;
		font-size: 28rpx;
		border: 1rpx solid #e0e6ff;
	}

	.popup-footer {
		display: flex;
		justify-content: space-between;
	}

	.cancel-btn,
	.confirm-btn {
		flex: 1;
		padding: 20rpx 0;
		border-radius: 50rpx;
		font-size: 28rpx;
		font-weight: bold;
	}

	.cancel-btn {
		background: #f8f9ff;
		color: #666;
		margin-right: 20rpx;
	}

	.confirm-btn {
		background: linear-gradient(to right, #4a6ef5, #6a5af9);
		color: white;
	}

	.contact-info {
		margin-top: 30rpx;
		font-size: 24rpx;
		color: #999;
		text-align: center;
		line-height: 1.6;
	}

	/* 动画效果 */
	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.animate__animated {
		animation-duration: 0.5s;
		animation-fill-mode: both;
	}

	.animate__fadeIn {
		animation-name: fadeIn;
	}

	.animate__delay-1s {
		animation-delay: 0.3s;
	}

	.animate__delay-2s {
		animation-delay: 0.6s;
	}
</style>